package com.mvc.app.implementations;

import com.container.app.annotations.Component;
import com.container.app.annotations.Inject;
import com.mvc.app.Model;
import com.mvc.app.ModelView;
import com.mvc.app.TemplateReader;
import com.mvc.app.ViewGenerator;
import com.mvc.app.utils.MVCUtils;
import org.antlr.stringtemplate.StringTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Georgiana.Scarlat
 * Date: 9/3/12
 * Time: 11:58 AM
 */
@Component
public class ViewGeneratorImpl implements ViewGenerator {

    private TemplateReader templateReader;

    @Inject
    public void setTemplateReader(TemplateReader templateReader) {
        this.templateReader = templateReader;
    }

    public void generateView(ModelView modelView, HttpServletResponse response) throws IOException {

        if (!hasValidView(modelView)) return;

        StringTemplate viewTemplate = templateReader.readTemplate(modelView.getHtmlViewFileName());

        if (hasValidModel(modelView)) {
            viewTemplate.reset();
            viewTemplate.setAttributes(appendAttributes(modelView));
        }

        PrintWriter writer = response.getWriter();
        writer.print(viewTemplate.toString());
    }

    private boolean hasValidModel(ModelView modelView) {
        Model model = modelView.getModel();
        Map<String, ?> beans = model == null ? null : model.getBeans();
        Map<String, ?> properties = model == null ? null : model.getProperties();
        return !(model == null || beans == null || properties == null || (beans.isEmpty() && properties.isEmpty()));

    }

    private boolean hasValidView(ModelView modelView) {
        String htmlViewFileName = modelView == null ? null : modelView.getHtmlViewFileName();
        return !(modelView == null || htmlViewFileName == null || MVCUtils.EMPTY_STRING.equals(htmlViewFileName));
    }

    private Map<String, Object> appendAttributes(ModelView modelView) {
        Map<String, Object> attributes = new HashMap<String, Object>(modelView.getModel().getBeans());
        attributes.putAll(modelView.getModel().getProperties());
        return attributes;
    }


}
